export default function useMap(id) {
  let bmap = null

  const overlayList = {
    deseauForm: [],
    drawPierced: [],
    diyGraph: [],
    drawIcon: [],
    drawLabel: [],
    drawCircle: [],
    drawPolyline: []
  }
  const viewList = {
    heatmaps: []
  }

  // 记录地图实例
  function setFn() {
    if (bmap !== null) return
    bmap = id ? window[`bmap_${id}`] : window['bmap_mapContainer']
  }

  // 地图中心初始化
  function setCenterAndZoom({ lng, lat, zoom }) {
    bmap.centerAndZoom(new window.BMapGL.Point(lat, lng), zoom)
  }
  // 中心缩放
  function setZoom(size) {
    bmap.setZoom(size)
  }
  // 中心定位
  function flyTo({ lng, lat, zoom }) {
    bmap.flyTo(new window.BMapGL.Point(lat, lng), zoom)
  }

  // 通过名字获取行政区域边界
  function getBoundary(area, rsIdx) {
    return new Promise((resolve, reject) => {
      const bdary = new window.BMapGL.Boundary()
      try {
        bdary.get(area, (rs) => {
          if (rs.boundaries.length === 0) {
            resolve([])
          } else {
            resolve(rs.boundaries[rsIdx])
          }
        })
      } catch (error) {
        reject('找不到区域边界')
      }
    })
  }

  // 绘制内容
  function addOverlay(ply, id, type) {
    ply.mark = {
      id,
      type
    }
    bmap.addOverlay(ply)
    if (overlayList[type] !== undefined) {
      overlayList[type].push(ply)
    } else {
      overlayList[type] = [ply]
    }
  }

  // 消除绘制内容
  function clearOverlay(_type = null, ids = []) {
    let plys = []
    // 不传类型全部清除，只传类型清除对应类型，ids也传则清除只对应id
    if (_type === null) {
      Object.values(overlayList)
        .flat()
        .forEach((item) => {
          item.bmap.removeOverlay(item)
        })
      for (let key in overlayList) {
        overlayList[key] = []
      }
    } else if (ids.length !== 0) {
      plys = overlayList[_type].filter((item) => ids.includes(item.mark.id))
      plys.forEach((item) => {
        bmap.removeOverlay(item)
      })
      overlayList[_type] = overlayList[_type].filter((item) => !ids.includes(item.mark.id))
    } else {
      plys = overlayList[_type]
      plys.forEach((item) => {
        bmap.removeOverlay(item)
      })
      overlayList[_type] = []
    }
  }

  // 反向覆盖物
  function drawReseau(opt) {
    setFn()
    opt = {
      id: 'deseauForm', // id
      ponits: [], // 点位二维数组
      fillColor: 'rgba(0,0,0,0)', // 遮罩层颜色
      fillOpacity: 0.5, // 遮罩层透明度
      ...opt,
      type: 'deseauForm' // 固定类型
    }
    const EN_JW = '180,90;' //东北角
    const NW_JW = '-180,90;' //西北角
    const WS_JW = '-180,-90;' //西南角
    const SE_JW = '180,-90;' //东南角

    const ply = new window.BMapGL.Polygon([SE_JW + WS_JW + NW_JW + EN_JW + SE_JW, ...opt.ponits], {
      strokeColor: 'none',
      fillColor: opt.fillColor,
      fillOpacity: opt.fillOpacity,
      strokeOpacity: 0
    })
    addOverlay(ply, opt.id, opt.type)
  }
  // 镂空覆盖物
  function drawPierced(opt) {
    setFn()
    opt = {
      id: 'drawPierced', // id
      ponits: [], // 点位二维数组
      fillColor: 'rgba(0,0,0,0)', // 遮罩层颜色
      fillOpacity: 0.5, // 遮罩层透明度
      ...opt,
      type: 'drawPierced' // 固定类型
    }
    const ply = new window.BMapGL.Polygon([opt.ponits[0], ...opt.ponits[1]], {
      strokeColor: 'none',
      fillColor: opt.fillColor,
      fillOpacity: opt.fillOpacity,
      strokeOpacity: 0
    })
    addOverlay(ply, opt.id, opt.type)
  }
  // 多边形
  function drawDiyGraph(opt) {
    setFn()
    opt = {
      id: 'diyGraph', // id
      ponits: [], // 点位集
      fillColor: '#fff', // 背景颜色
      fillOpacity: 0.7, // 透明度
      strokeWeight: 3,
      strokeColor: 'pink',
      onClick: null,
      ...opt,
      type: 'diyGraph' // 固定类型
    }

    const ply = new window.BMapGL.Polygon(opt.ponits, {
      fillColor: opt.fillColor,
      fillOpacity: opt.fillOpacity,
      strokeWeight: opt.strokeWeight,
      strokeColor: opt.strokeColor
    })

    opt.onClick && ply.addEventListener('click', () => opt.onClick(ply))
    addOverlay(ply, opt.id, opt.type)
  }
  // 标签
  function drawIcon(opt) {
    setFn()
    opt = {
      id: 'drawIcon', // id
      point: [],
      iconSize: ['20px', '20px'],
      iconPot: [0, 0],
      icon: '',
      onClick: null,
      ...opt,
      type: 'drawIcon' // 固定类型
    }
    const pt = new window.BMapGL.Point(opt.point[0], opt.point[1])
    const myIcon = opt.icon
      ? new window.BMapGL.Icon(opt.icon, new window.BMapGL.Size(opt.iconSize[0], opt.iconSize[1]))
      : null
    const marker = new window.BMapGL.Marker(pt, {
      icon: myIcon,
      offset: new window.BMapGL.Size(opt.iconPot[0], opt.iconPot[1])
    })
    opt.onClick && marker.addEventListener('click', () => opt.onClick(marker))

    addOverlay(marker, opt.id, opt.type)
  }
  // 文本
  function drawLabel(opt) {
    setFn()
    opt = {
      id: 'drawLabel', // id
      point: [],
      labelPot: [-20, 0],
      label: '',
      size: 16,
      color: '#fff',
      bgColor: '#00000069',
      onClick: null,
      ...opt,
      type: 'drawLabel' // 固定类型
    }
    const pt = new window.BMapGL.Point(opt.point[0], opt.point[1])
    // 标注创建
    const label = new window.BMapGL.Label(opt.label, {
      position: pt,
      offset: new window.BMapGL.Size(opt.labelPot[0], opt.labelPot[1])
    })
    // 标注样式设置
    label.setStyle({
      fontSize: opt.size,
      color: opt.color,
      backgroundColor: opt.bgColor,
      borderColor: 'transparent'
    })
    opt.onClick && label.addEventListener('click', () => opt.onClick(label))
    addOverlay(label, opt.id, opt.type)
  }
  // 圆形
  function drawCircle(opt) {
    setFn()
    opt = {
      id: 'drawCircle', // id
      point: [],
      radius: 10000,
      strokeColor: '#fff',
      fillColor: 'pink',
      strokeWeight: 3,
      onClick: null,
      ...opt,
      type: 'drawCircle' // 固定类型
    }
    const pt = new window.BMapGL.Point(opt.point[0], opt.point[1])
    const circle = new window.BMapGL.Circle(pt, opt.radius, {
      strokeColor: opt.strokeColor,
      fillColor: opt.fillColor,
      strokeWeight: opt.strokeWeight
    })
    opt.onClick && circle.addEventListener('click', () => opt.onClick(circle))
    addOverlay(circle, opt.id, opt.type)
  }
  // 折线
  function drawPolyline(opt) {
    setFn()
    opt = {
      id: 'drawPolyline', // id
      points: [],
      strokeColor: 'red',
      strokeWeight: 3,
      onClick: null,
      ...opt,
      type: 'drawPolyline' // 固定类型
    }
    const points = opt.points.map((item) => {
      return new window.BMapGL.Point(item[0], item[1])
    })
    const polyline = new window.BMapGL.Polyline(points, {
      strokeColor: opt.strokeColor,
      strokeWeight: opt.strokeWeight
    })
    opt.onClick && polyline.addEventListener('click', () => opt.onClick(polyline))
    addOverlay(polyline, opt.id, opt.type)
  }

  // 热力图
  function drawHeatMap(opt) {
    opt = {
      size: 6000, // 单个点绘制大小
      max: 20, // 最大阈值
      height: 0, // 最大高度，默认为0
      unit: 'm', // 单位，m:米，px: 像素
      gradient: {
        // 对应比例渐变色
        0.25: 'rgba(0, 0, 255, 1)',
        0.55: 'rgba(0, 255, 0, 1)',
        0.85: 'rgba(255, 255, 0, 1)',
        1: 'rgba(255, 0, 0, 1)'
      },
      data: [
        {
          geometry: {
            type: 'Point',
            coordinates: ['12602748', '2629534']
          },
          properties: {
            count: '20'
          }
        }
      ],
      ...opt
    }
    setFn()
    const view = new window.mapvgl.View({
      map: bmap
    })
    const heatmap = new window.mapvgl.HeatmapLayer(opt)
    view.addLayer(heatmap)
    // setTimeout(() => {
    //   view.removeLayer(heatmap)
    // }, 1000)
  }
  return {
    setFn,
    setZoom,
    flyTo,
    setCenterAndZoom,
    getBoundary,
    drawReseau,
    clearOverlay,
    drawDiyGraph,
    drawIcon,
    drawLabel,
    drawCircle,
    drawPolyline,
    drawPierced,
    drawHeatMap
    // drawReseauFormPoint,
    // clearDrawReseau
  }
}
